import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DialogService, DrawerService, IDrawerOpenResult, TableWidthConfig } from '@devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { LogComponent } from 'src/app/@shared/components/log/log.component';

@Component({
  selector: 'app-other-inventory',
  templateUrl: './other-inventory.component.html',
  styleUrls: ['./other-inventory.component.scss']
})
export class OtherInventoryComponent {
 value1 = [];
  tableData:any[]=[]
  ingredientDetail: any[] = []; // 食材详情数据
  splitBarSize = '1px';
  partDetailHeight = '50%';
  OtherWarehousingNum:string =''
  DateTime:any=null
  startTime:any=null
  endTime:any=null
  allCheckedStatus = false;
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  checkedIds = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  msgs: { severity: any; summary: any; content: any; }[];
  config = {
    id: 'Add-role',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  filterValue:string = '';
  TreeData:any = [];
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  state: any;
  constructor(private dialogService: DialogService,private SharedMethodService:SharedMethodService,private Router:Router,private StorehouseService: StorehouseService,private DrawerService:DrawerService){}
  ngOnInit(): void {
    this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '食材入库单号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '入库日期',
        fieldType: 'text',
      },
      {
        field: '状态',
        header: '入库状态',
        fieldType: 'text'
      },
      {
        field: '审核',
        header: '审核状态',
        fieldType: 'text'
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text'
      },
      {
        field: 'name',
        header: '制单人',
        fieldType: 'text'
      },
      {
        field: 'name',
        header: '制单日期',
        fieldType: 'text'
      },
      {
        field: 'name',
        header: '日志',
        fieldType: 'text'
      },
    ]
  };//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field:'name',
      width:'180px'
    },
    {
      field:'name',
      width:'160px'
    },
    {
      field:'name',
      width:'150px'
    },
    {
      field:'name',
      width:'150px'
    },
    {
      field:'name',
      width:'150px'
    },
    {
      field:'name',
      width:'150px'
    },
    {
      field:'name',
      width:'150px'
    },
    {
      field:'name',
      width:'100px'
    },
    {
      field:'name',
      width:'100px'
    },
  ];//表格宽度配置
  // 食材详情表格宽度配置
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: 'ingredientCode',
      width: '120px'
    },
    {
      field: 'ingredientName',
      width: '150px'
    },
    {
      field: 'specification',
      width: '120px'
    },
    {
      field: 'description',
      width: '200px'
    },
    {
      field: 'quantity',
      width: '100px'
    },
    {
      field: 'unit',
      width: '80px'
    },
    {
      field: 'unitPrice',
      width: '100px'
    },
    {
      field: 'totalAmount',
      width: '120px'
    },
    {
      field: 'productionDate',
      width: '120px'
    },
    {
      field: 'shelfLife',
      width: '100px'
    },
    {
      field: 'expiryDate',
      width: '120px'
    },
    {
      field: 'storageLocation',
      width: '120px'
    },
    {
      field: 'remark',
      width: '150px'
    }
  ];
  // 显示入库单详情
  showDetail(rowItem: any, rowIndex: number) {
    // 模拟获取食材详情数据，实际项目中应该调用后端API
    this.ingredientDetail = this.mockIngredientDetail(rowItem);
  }

  // 模拟食材详情数据
  mockIngredientDetail(orderItem: any) {
    return [
      {
        ingredientCode: 'FOOD001',
        ingredientName: '大白菜',
        specification: '500g/袋',
        description: '新鲜大白菜，产地山东',
        quantity: 100,
        unit: '袋',
        unitPrice: 3.50,
        totalAmount: 350.00,
        productionDate: new Date('2025-01-20'),
        shelfLife: 7,
        expiryDate: new Date('2025-01-27'),
        storageLocation: 'A区-01-001',
        remark: '测试用食材'
      },
      {
        ingredientCode: 'FOOD002',
        ingredientName: '土豆',
        specification: '1kg/袋',
        description: '优质土豆，产地内蒙古',
        quantity: 50,
        unit: '袋',
        unitPrice: 4.20,
        totalAmount: 210.00,
        productionDate: new Date('2025-01-18'),
        shelfLife: 30,
        expiryDate: new Date('2025-02-17'),
        storageLocation: 'A区-01-002',
        remark: '炒菜机器人专用'
      },
      {
        ingredientCode: 'FOOD003',
        ingredientName: '胡萝卜',
        specification: '800g/袋',
        description: '新鲜胡萝卜，营养丰富',
        quantity: 75,
        unit: '袋',
        unitPrice: 2.80,
        totalAmount: 210.00,
        productionDate: new Date('2025-01-19'),
        shelfLife: 15,
        expiryDate: new Date('2025-02-03'),
        storageLocation: 'A区-01-003',
        remark: '机器人测试配菜'
      }
    ];
  }
  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
    this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }//切换页码
  pageSizeChange($event: any){
    this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }//改变每页显示数量
  DeleteRole(rowitem:any,dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除食材入库单',
      content: '确认删除该食材入库单据吗？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
           this.StorehouseService.DeleteOtherWarehousingModel(rowitem.otherWarehousingModelId).subscribe((data:any)=>{
            this.StorehouseService.getWarehouseById(rowitem.warehouseId).subscribe((data:any)=>{
              rowitem.warehouseName = data.warehouseName
            })
            this.showToast('success','成功','食材入库单删除成功')

           },(error) => {
            if(error.status==404){
              this.showToast('error', '失败', '服务器连接失败');
            }else{
              this.showToast('error', '失败', error.error);
            }
          })
           results.modalInstance.hide();
           this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
            this.tableData = data.items
            this.pager.total = data.totalCount
          })
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//删除食材入库单
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  add(){
    this.Router.navigate(['/pages/inventory/other-inventory/add'])
  }//新增食材入库
  edit(id:any){
    this.Router.navigate(['/pages/inventory/other-inventory/edit', id]);
  }
  filter(){
    this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }//查询食材
  reset(){
    this.OtherWarehousingNum=''
    this.DateTime=null
    this.startTime=null
    this.endTime=null
    this.value1 =[]
    this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tableData = data.items
      this.pager.total = data.totalCount
    })
  }//重置食材查询
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }){
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable,'workshopId').subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }//获取选中行
  cleared(){
    this.SharedMethodService.cleared(this.checkedIds,this.tableData,this.datatable).subscribe((data:any)=>{
      this.checkedIds=data;

    })
  }//清空选中行
  start$end(){
    this.startTime = this.value1[0].toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/');
    this.endTime = this.value1[1].toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/');
  }
  detailed(id:any){
    this.Router.navigate(['/pages/inventory/other-inventory/details', id]);
  }
  ruku(id:any){
    this.StorehouseService.ReceiptOtherWarehousingItems(id).subscribe((data:any)=>{
      this.showToast('success','成功',"食材入库成功")
      this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tableData = data.items
        this.pager.total = data.totalCount
      }
    )
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//食材入库操作
  DownloadOtherWarehousingFileModel(){
    this.StorehouseService.DownloadOtherWarehousingFileModel().subscribe((data:any)=>{
      // 创建一个新的 Blob 对象
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

      // 创建一个指向 Blob 的 URL
      const url = window.URL.createObjectURL(blob);

      // 创建一个新的 <a> 元素并点击它来开始下载
      const link = document.createElement('a');
      link.href = url;
      link.download = '食材入库单模板.xlsx';  // 设置下载文件的名称
      link.click();

      // 释放 URL
      window.URL.revokeObjectURL(url);

      this.showToast('success','成功','下载成功')
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//下载食材入库模板
  onFileSelected(event: any) {
    const file = event.target.files[0];
    this.StorehouseService.ImportOtherWarehousingFromExcel(file).subscribe(
      (response) => {
        this.showToast('success','成功',"食材数据导入成功")
        this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
          this.tableData = data.items
          this.pager.total = data.totalCount
        })
      },
      (error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
    );
    event.target.value = null;  // 重置 input 元素的值
  }
  isAudit(rowitem:any){
    this.StorehouseService.AuditOtherWarehousingModel(rowitem.otherWarehousingModelId).subscribe((data:any)=>{
      this.showToast('success','成功','食材入库单审核成功')
      this.StorehouseService.GetOtherWarehousingModelsPaged(this.OtherWarehousingNum,this.DateTime,this.startTime,this.endTime,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tableData = data.items
        this.pager.total = data.totalCount
      })
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//审核食材入库单
  results: IDrawerOpenResult;
  GetLogs(){
    this.StorehouseService.GetAllOtherWarehousingLogs(1,9999).subscribe((data:any)=>{
      const logData = data.items
      const columns =  [
        {
          field: '生产入库单号',
          header: '生产入库单号',
          fieldType: 'text'
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text'
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text'
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text'
        }
      ]

      this.results = this.DrawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: {data:logData,columns:columns},
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {

        },
      });
    })
  }
  GetLogById(rowItem:any){
    this.StorehouseService.GetLogsByOtherWarehousingId(rowItem.otherWarehousingModelId,1,9999).subscribe((data:any)=>{
      const logData = data.items
      const columns =  [
        {
          field: '生产入库单号',
          header: '生产入库单号',
          fieldType: 'text'
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text'
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text'
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text'
        }
      ]

      this.results = this.DrawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: {data:logData,columns:columns},
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {

        },
      });
    })
  }
}
